package com.xzl.xep.dao.hibernate;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.property.ChainedPropertyAccessor;
import org.hibernate.property.PropertyAccessor;
import org.hibernate.property.PropertyAccessorFactory;
import org.hibernate.property.Setter;
import org.hibernate.transform.ResultTransformer;

/**
 * 自定义的数据库字库转换成POJO
 */

@SuppressWarnings("rawtypes")
public class EscResultToBean implements ResultTransformer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	


	private final Class resultClass;
	private Setter[] setters;
	private Class[] types;
	private PropertyAccessor propertyAccessor;

	
	public EscResultToBean(Class resultClass) {
		if (resultClass == null) {
			throw new IllegalArgumentException("resultClass cannot be null");
		}
		this.resultClass = resultClass;
		this.propertyAccessor = new ChainedPropertyAccessor(
				new PropertyAccessor[] {
						PropertyAccessorFactory.getPropertyAccessor(
								resultClass, null),
						PropertyAccessorFactory.getPropertyAccessor("field") });
	
	}

	//结果转换时，HIBERNATE调用此方法
	public Object transformTuple(Object[] tuple, String[] aliases) {
		Object result;
		
		try {
			if(setters==null || types ==null) {//首先初始化，取得目标POJO类的所有SETTER方法 和 数据类型
				setters = new Setter[aliases.length];
				types = new Class[aliases.length];
				for (int i = 0; i < aliases.length; i++) {
					String alias = aliases[i];
					if(alias != null) {
						//我的逻辑主要是在getSetterByColumnName方法里面，其它都是HIBERNATE的另一个类中COPY的
						//这里填充所需要的SETTER方法
						getSetterByColumnName(alias, i);
					}
				}
			}
			result = resultClass.newInstance();
			
			//这里使用SETTER方法填充POJO对象
			for (int i = 0; i < aliases.length; i++) {
				if(setters[i]!=null && types[i]!=null) {
					Object value ;
					if(types[i] == String.class){
						if(tuple[i] instanceof String)	value = tuple[i];
						else if(tuple[i] instanceof BigDecimal) value = ((BigDecimal)tuple[i]).toString();
						else value = tuple[i];
					}else if(types[i] == Long.class){
						if(tuple[i]==null) value = new Long(0);
						else value = ((BigDecimal)tuple[i]).longValue();
					}else if(types[i] == Double.class){
						if(tuple[i]==null) value = new Double(0d);
						else value = ((BigDecimal)tuple[i]).doubleValue();
					}else if(types[i] == Integer.class){
						if(tuple[i]==null) value = new Integer(0);
						else value = ((BigDecimal)tuple[i]).intValue();
					}else{
						value = tuple[i];
					}
					setters[i].set(result, value, null);
				}
			}
		} catch (InstantiationException e) {
			throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName());
		} catch (IllegalAccessException e) {
			throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName());
		}
		
		return result;
	}

	//根据数据库字段名在POJO查找JAVA属性名，参数就是数据库字段名，如：USER_ID
	private void getSetterByColumnName(String alias, int i) {
		//取得POJO所有属性名
		Field[] fields = resultClass.getDeclaredFields();
		if(fields==null || fields.length==0){
			throw new RuntimeException("实体"+resultClass.getName()+"不含任何属性");
		}
		
		String proName = alias.toLowerCase();
		for (Field field : fields) {
			if(field.getName().toLowerCase().equals(proName)){//去除下杠的字段名如果和属性名对得上，就取这个SETTER方法
				types[i] = field.getType();
				setters[i] = propertyAccessor.getSetter(resultClass, field.getName());
				return ;
			}
		}
		throw new RuntimeException("找不到数据库字段 ："+ alias + " 对应的POJO属性或其getter方法");
	}


	public List transformList(List collection) {
		return collection;
	}

}

